package jsu.blogger.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; // 导入 JavaTimeModule
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    // 创建 ObjectMapper 实例并注册 JavaTimeModule
    private final ObjectMapper objectMapper;

    @Autowired
    public RedisService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.objectMapper = new ObjectMapper();
        this.objectMapper.registerModule(new JavaTimeModule()); // 注册 JavaTimeModule
    }

    // 向 Redis 中存储一个键值对
    public void setValue(String key, Object value) {
        try {
            // 将对象序列化为 JSON 字符串
            String jsonValue = objectMapper.writeValueAsString(value);
            redisTemplate.opsForValue().set(key, jsonValue);
        } catch (IOException e) {
            System.out.println("Error serializing value: " + e.getMessage());
        }
    }

    // 从 Redis 中获取指定键的值
    public <T> T getValue(String key, Class<T> valueType) {
        String jsonValue = (String) redisTemplate.opsForValue().get(key);
        if (jsonValue != null) {
            try {
                // 将 JSON 字符串反序列化为对象
                return objectMapper.readValue(jsonValue, valueType);
            } catch (IOException e) {
                System.out.println("Error deserializing value: " + e.getMessage());
            }
        }
        return null; // 或者抛出异常，视具体需求而定
    }

    // 向 Redis 中存储一个键值对，并设置其过期时间
    public void setValueWithExpiry(String key, Object value, long timeout, TimeUnit timeUnit) {
        setValue(key, value);
        redisTemplate.expire(key, timeout, timeUnit);
    }

    // 从 Redis 中删除指定键及其对应的值
    public void deleteValue(String key) {
        redisTemplate.delete(key);
    }
}
